package com.mask.sca.auth.security;



import com.mask.sca.auth.entity.SecurityUser;
import com.mask.sca.core.entity.RoleDTO;
import com.mask.sca.core.entity.UserDTO;
import com.mask.sca.core.response.ApiResponse;
import com.mask.sca.member.api.feign.FeignMemberService;
import com.mask.sca.system.api.feign.FeignSystemService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.ArrayList;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private FeignMemberService memberService;

    @Resource
    private FeignSystemService systemService;

    @Override
    public UserDetails loadUserByUsername(String user) throws UsernameNotFoundException {
        String[] split = user.split(":");
        String username = split[0];
        String loginType = split[1];
        ApiResponse<UserDTO> dtor = new ApiResponse<>();
        if ("admin".equals(loginType)){
            dtor= systemService.loadByUsername(username);
        }else {
            dtor = memberService.loadByUsername(username);
        }

        if (dtor.getData() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 组装权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (dtor.getData().getRoles() != null) {
            for (RoleDTO role : dtor.getData().getRoles()) {
                authorities.add(new SimpleGrantedAuthority(role.getRoleCode()));
            }
        }
        UserDTO currentUserInfo = dtor.getData();
        System.out.println("CustomUserDetailsService: authorities=" + authorities);
        SecurityUser securityUser = new SecurityUser(
                currentUserInfo.getUsername(),
                currentUserInfo.getPassword(),
                true,
                true,
                true,
                true,
                AuthorityUtils.commaSeparatedStringToAuthorityList(null));
        securityUser.setId(currentUserInfo.getId());
        securityUser.setUserType(currentUserInfo.getUserType());
        securityUser.setAuthStatus(currentUserInfo.getAuthStatus());
        securityUser.setAvatar(currentUserInfo.getAvatar());
        securityUser.setSex(currentUserInfo.getSex());
        securityUser.setNickName(currentUserInfo.getNickName());
        securityUser.setBirthday(currentUserInfo.getBirthday());
        return securityUser;
    }
} 